import React, { useState, useEffect } from "react";
import {
  Table,
  Space,
  Button,
  Input,
  Modal,
  Form,
  message,
  Select,
  TreeSelect
} from "antd";
import {
  SearchOutlined,
  PlusOutlined,
  EditOutlined,
  DeleteOutlined
} from "@ant-design/icons";
import { addMenu, getMenuList } from "@/services/requestServices";

interface MenuItem {
  id: string;
  name: string;
  path: string;
  parentId: string | null;
  order: number;
  type: "M" | "C" | "F";
  permission: string;
  status: "0" | "1";
  children?: MenuItem[];
}

const MenuManagement: React.FC = () => {
  const [menus, setMenus] = useState<MenuItem[]>([]);
  const [loading, setLoading] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);
  const [form] = Form.useForm();
  const [editingId, setEditingId] = useState<string | null>(null);

  // 获取菜单列表
  const fetchMenus = async () => {
    try {
      setLoading(true);
      const response = await getMenuList();
      console.log(response, "infotttt");
      const data = response.rows;
      setMenus(data);
    } catch (error) {
      message.error("获取菜单列表失败");
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchMenus();
  }, []);

  // 添加或更新菜单
  const handleSubmit = async (values: any) => {
    addMenu(values).then(res => {
      console.log(res, "infotttt");
      try {
        if (res.code === 200) {
          message.success(`${editingId ? "更新" : "添加"}菜单成功`);
          setModalVisible(false);
          form.resetFields();
          fetchMenus();
        } else {
          message.error(`${editingId ? "更新" : "添加"}菜单失败`);
        }
      } catch (error) {
        message.error(`${editingId ? "更新" : "添加"}菜单失败`);
      }
    });
  };

  // 删除菜单
  const handleDelete = async (id: string) => {
    Modal.confirm({
      title: "确认删除",
      content: "确定要删除这个菜单吗？如果是父菜单，其下所有子菜单也会被删除。",
      cancelText: "取消",
      okText: "确定",
      onOk: async () => {
        try {
          const response = await fetch(`/menus/${id}`, {
            method: "DELETE"
          });

          if (response.ok) {
            message.success("删除菜单成功");
            fetchMenus();
          }
        } catch (error) {
          message.error("删除菜单失败");
        }
      }
    });
  };

  // 转换菜单数据为树形选择数据
  const getTreeData = (data: MenuItem[]): any[] => {
    return data.map(item => ({
      title: item.name,
      value: item.id,
      children: item.children ? getTreeData(item.children) : undefined
    }));
  };

  const columns = [
    {
      title: "菜单名称",
      dataIndex: "name",
      key: "name"
    },
    {
      title: "路径",
      dataIndex: "path",
      key: "path"
    },
    {
      title: "类型",
      dataIndex: "menuType",
      key: "menuType",
      render: (type: string) => {
        const typeMap = {
          M: "目录",
          C: "菜单",
          F: "按钮"
        };
        return typeMap[type as keyof typeof typeMap] || type;
      }
    },
    {
      title: "状态",
      dataIndex: "status",
      key: "status",
      render: (status: string) => (status === "0" ? "正常" : "停用")
    },
    {
      title: "排序",
      dataIndex: "order",
      key: "order"
    },
    {
      title: "权限标识",
      dataIndex: "permission",
      key: "permission"
    },
    {
      title: "操作",
      key: "action",
      render: (_: any, record: MenuItem) => (
        <Space size="middle">
          <Button
            type="link"
            icon={<EditOutlined />}
            onClick={() => {
              setEditingId(record.id);
              form.setFieldsValue(record);
              setModalVisible(true);
            }}
          >
            编辑
          </Button>
          <Button
            type="link"
            danger
            icon={<DeleteOutlined />}
            onClick={() => handleDelete(record.id)}
          >
            删除
          </Button>
        </Space>
      )
    }
  ];

  return (
    <div style={{ padding: 24 }}>
      <div style={{ marginBottom: 16 }}>
        <Space>
          <Input
            placeholder="搜索菜单"
            prefix={<SearchOutlined />}
            style={{ width: 200 }}
            onChange={e => {
              const searchText = e.target.value.toLowerCase();
              const filterMenus = (items: MenuItem[]): MenuItem[] => {
                return items.filter(item => {
                  const match =
                    item.name.toLowerCase().includes(searchText) ||
                    item.path.toLowerCase().includes(searchText);
                  if (match) return true;
                  if (item.children) {
                    const filteredChildren = filterMenus(item.children);
                    if (filteredChildren.length) {
                      item.children = filteredChildren;
                      return true;
                    }
                  }
                  return false;
                });
              };
              const filtered = filterMenus([...menus]);
              setMenus(filtered);
            }}
          />
          <Button
            type="primary"
            icon={<PlusOutlined />}
            onClick={() => {
              setEditingId(null);
              form.resetFields();
              setModalVisible(true);
            }}
          >
            添加菜单
          </Button>
        </Space>
      </div>

      <Table
        columns={columns}
        dataSource={menus}
        rowKey="id"
        loading={loading}
      />

      <Modal
        title={editingId ? "编辑菜单" : "添加菜单"}
        open={modalVisible}
        width={600}
        cancelText="取消"
        okText="确定"
        onCancel={() => {
          setModalVisible(false);
          form.resetFields();
        }}
        onOk={() => form.submit()}
      >
        <Form form={form} layout="vertical" onFinish={handleSubmit}>
          <Form.Item
            name="menuName"
            label="菜单名称"
            rules={[{ required: true, message: "请输入菜单名称" }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="path"
            label="路径"
            rules={[{ required: true, message: "请输入路径" }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="menuType"
            label="类型"
            rules={[{ required: true, message: "请选择类型" }]}
          >
            <Select>
              <Select.Option value="M">目录</Select.Option>
              <Select.Option value="C">菜单</Select.Option>
              <Select.Option value="F">按钮</Select.Option>
            </Select>
          </Form.Item>
          <Form.Item name="status" label="菜单状态" initialValue="0">
            <Select>
              <Select.Option value="0">正常</Select.Option>
              <Select.Option value="1">停用</Select.Option>
            </Select>
          </Form.Item>
          <Form.Item name="parentId" label="上级菜单">
            <TreeSelect
              treeData={getTreeData(menus)}
              placeholder="请选择上级菜单"
              allowClear
              treeDefaultExpandAll
            />
          </Form.Item>
          <Form.Item
            name="order"
            label="排序"
            rules={[{ required: true, message: "请输入排序号" }]}
          >
            <Input type="number" />
          </Form.Item>
          <Form.Item
            name="permission"
            label="权限标识"
            rules={[{ required: true, message: "请输入权限标识" }]}
          >
            <Input />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default MenuManagement;
